<template>
  <div class="m-4" style="background-color: #F1FAEE;margin-top: 3%">
    <el-form :model="formData" ref="formDataRef" label-width="100px" class="mt-4">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formData.title"></el-input>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <quill-editor  @update:content="updateContent" :options="editorOptions" style="width: 100%; height: 500px"></quill-editor>
      </el-form-item>

      <el-form-item label="上传封面">
        <input type="file" @change="handleFileUpload" class="custom-file-upload" :disabled="buttoncontrol">
  <el-avatar shape="square" :size="50" :src="formData.coverImg"></el-avatar>
      </el-form-item>
      <el-form-item label="文章分类">
        <el-cascader
            v-model="value"
            :options="options"
            :props="props"
            @change="changeCategory"
        />
      </el-form-item>

      <el-form-item label="文章状态">
        <el-radio-group  style="width: 100%" v-model="formData.state"  size="large" >
          <el-radio-button label="已发布"  />
          <el-radio-button label="草稿"  />
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitArticle">发布文章</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.el-input__inner {
  height: 200px; /* Set the height of the textarea */
  resize: vertical; /* Allow vertical resizing */
}

.el-input {
  width: 100%; /* Make the textarea occupy the full width */
}
.ql-editor {
  height: 400px; /* 设置编辑器内容区域的高度 */
}
.custom-file-upload {
  display: inline-block;
  padding: 10px 20px;
  cursor: pointer;
  background-color: #337ab7;
  color: white;
  border: 2px solid #337ab7;
  border-radius: 5px;
  text-align: center;
}

.custom-file-upload:hover {
  background-color: #286090;
}

.custom-file-upload input[type="file"] {
  display: none;
}
</style>
<script setup>
import {h, onMounted, reactive, ref} from 'vue'
import axios from "axios";
import {ElNotification, ElForm, ElFormItem, ElInput, ElButton, ElMessage} from "element-plus";
const radio1=ref("已发布")
const value = ref([])
const formData = ref({
  title: '',
  content: '',
  coverImg:'',
  categoryId:'',
  allcategoryId:'',
  state:''
})
const updateContent=(newContent) =>{

// 假设 data 是包含 Delta2 对象的变量

// 使用 Object.values() 方法获取 Delta2 对象的所有值组成的数组
  const deltaValues = Object.values(newContent);

// 获取数组中第一个元素的值
  const firstValue = deltaValues[0];
formData.value.content=firstValue[0].insert
  if (formData.value.content.length>10000){
    return ElMessage({
      type:"warning",
      message:"文章内容超出可接受大小 请在9999字以内"
    })
  }

}
//禁用button
const buttoncontrol=ref(false);
const changeCategory=()=>{
//处理分类id
  formData.value.allcategoryId=value.value[0]
  formData.value.categoryId=value.value[1]

}
const props = {
  // expandTrigger: 'hover'as const,
}

const handleFileUpload = (e) => {
  const file = e.target.files[0];
  if (file) {

    const FormData1 = new FormData();
    FormData1.append('file', file);
//准备文件数据
    // Make a POST request to upload the file
    axios.post('/upload', FormData1)
        .then(response => {
          //处理  const buttoncontrol=ref(false);
          buttoncontrol.value=true;
          // Handle the response, e.g., update the formData.coverImg with the image URL
          formData.value.coverImg=response.data.data
          return  ElNotification({
            title: '消息',
            message: h('i', { style: 'color: teal' },'封面上传成功'),
          })
        })
        .catch(error => {
          ElNotification({
            title: '消息',
            message: h('i', { style: 'color: teal' },'封面上传失败'),
          })
          console.error('Error uploading file:', error);
        }).finally(()=>{
      buttoncontrol.value=false;
    })
  }
}

const category = ref([]);
const options = ref([])
//配置富文本编辑器
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css';
// import {createRouter as roter} from "/vue-router/dist/vue-router.esm-browser.js";
import router from "@/utils/router.js";
// 定义一个响应式的 editorOptions 对象，其中包含了需要配置的选项参数
const editorOptions = reactive({
  modules: {
    toolbar: [  // 工具栏配置
      ['bold', 'italic', 'underline', 'strike'],  // 粗体、斜体、下划线、删除线
      [{ 'header': 1 }, { 'header': 2 }],  // 标题1和标题2
      [{ 'list': 'ordered' }, { 'list': 'bullet' }],  // 有序列表和无序列表
      [{ 'script': 'sub' }, { 'script': 'super' }],  // 上标和下标
      [{ 'indent': '-1' }, { 'indent': '+1' }],  // 缩进
      [{ 'direction': 'rtl' }],  // 文字方向
      [{ 'size': ['small', false, 'large', 'huge'] }],  // 字号
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],  // 标题等级
      [{ 'color': [] }, { 'background': [] }],  // 字体颜色和背景色
      [{ 'font': [] }],  // 字体
      [{ 'align': [] }],  // 对齐方式
      ['clean']  // 清除格式
    ]
  }
})
const getall = () => {
  axios.get("/allcategory").then(result => {
    console.log(result.data.data);
    category.value = result.data.data;

    // 根据category的值动态生成options
    options.value = generateOptions(result.data.data);
  }).catch(err => {
    ElNotification({
      title: '消息',
      message: h('i', { style: 'color: teal' }, '数据异常 请联系管理员'),
    });
  });
}

//下面这个方法对数据进行循环 返回为value和label 设置了分级联合查询
const generateOptions = (data) => {
  return data.map(item => {
    return {
      value: item.id,
      label: item.cindex,
      children: item.categoryList.map(it => {
        return {
          label: it.categoryName,
          value: it.id
        };
      })
    };
  });
}
//发布文章
const submitArticle=()=>{
  console.log("到这里")
let check=checkForm(formData)
  if (check){
    console.log(formData.value)
        axios.post("/article",formData.value).then(result=>{
      router.push("/list")
        return ElMessage({
          type:'success',
          message:"文章发布成功"
        })
             }).catch(error=>{
               return ElMessage({
                 type:'warning'
                 ,
                 message:"文章发布失败"
               })
        })

  }else {
    ElMessage({
      type:'warning',
      message:"文章信息不完整 不能为空"
    })
  }
}
const checkForm=(formdata)=>{
  if (formdata.value.title!=null&&formdata.value.coverImg!=null&&formdata.value.categoryId!=null&&formdata.value.allcategoryId!=null&&formdata.value.content!=null){

    return true;
  }
  else {

    return false
  }
}

onMounted(() => {
  getall()
})
</script>
